﻿using AutoMapper;
using RestApp.UI.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using modelViews = RestApp.UI.Models;
using domain = RestApp.BusinessLogic;
using RestApp.UI.Helpers;

namespace RestApp.UI.Controllers
{
    [Authorize]
    public class ManageUsersController : Controller
    {
        private IBusinessFactory _factory;
        public ManageUsersController(IBusinessFactory factory)
        {
            _factory = factory;
        }

        [Authorize]
        public ActionResult List()
        {
            var dbUsers = _factory.UsersLogic.GetAllFilteredByLoginCredentials(User.Identity.Name).ToList();
            var mapedCollection = Mapper.Map<IEnumerable<domain.User>, IEnumerable<modelViews.User>>(dbUsers);
            return View(mapedCollection);
        }

		[Authorize(Roles = "Admin")]
        public ActionResult Add()
        {
            FillDdls();
            return View();
        }

        [HttpPost]
		[Authorize(Roles = "Admin")]
        public ActionResult Add(modelViews.User user)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Пожалуйста, исправьте ошибки");
                FillDdls();
                return View(user);
            }
            if (_factory.UsersLogic.IsLoginExists(user.Login))
            {
                ModelState.AddModelError("Login", "Такой логин уже зарегистрирован");
                FillDdls();
                return View(user);
            }
            user.Password = PasswordHelper.CreateRandomPassword();
            var mapperUser = Mapper.Map<modelViews.User, domain.User>(user);
            try
            {
                _factory.UsersLogic.Add(mapperUser);
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Произошла ошибка. Попробуйте перезагрузить страницу");
                return View(user);
            }
            return RedirectToAction("List");
        }

        private void FillDdls(int idRole = 1, int idJobTitle = 1, int idBossJobPost = 1)
        {
            FillRolesDdl(idRole);
			FillJobTitlesDdls(idJobTitle, "jobTitles");
			FillJobTitlesDdls(idBossJobPost, "jobBossTitles");
        }

        private void FillRolesDdl(int idRole)
        {
            var dbRoles = _factory.RolesLogic.GetAllRoles();
            var mapedRoles = Mapper.Map<IEnumerable<domain.Role>, IEnumerable<modelViews.Role>>(dbRoles);
            var selected = mapedRoles.FirstOrDefault(t => t.Id == idRole);
            ViewData["roles"] = new SelectList(mapedRoles, "Id", "Name", selected);
        }

        private void FillJobTitlesDdls(int idJobTitle, string key)
        {
            var dbJobTitles = _factory.JobTitlesLogic.GetAll();
            var mappedJobTitles = Mapper.Map<IEnumerable<domain.JobTitle>, IEnumerable<modelViews.JobTitle>>(dbJobTitles);
            var selected = mappedJobTitles.FirstOrDefault(t => t.Id == idJobTitle);
            ViewData[key] = new SelectList(mappedJobTitles, "Id", "Name", selected);
        }

		[Authorize(Roles = "Admin")]
        public ActionResult Delete(int id)
        {
            try
            {
                _factory.UsersLogic.RemoveById(id);
            }
            catch (Exception ex)
            {
                ViewData["error"] = "Ошибка при удалении пользователя: " + ex.Message;
            }
            return RedirectToAction("List");
        }

		[Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            var user = _factory.UsersLogic.GetById(id);
            var mappedUser = Mapper.Map<modelViews.EditableUser>(user);
            FillDdls(mappedUser.IdRole, mappedUser.IdJobPost);
            return View(mappedUser);
        }

        [HttpPost]
		[Authorize(Roles = "Admin")]
        public ActionResult Edit(modelViews.EditableUser user)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Пожалуйста, заполните форму корректными данными");
                FillDdls(user.IdRole, user.IdJobPost);
                return View(user);
            }
            var mappedUser = Mapper.Map<domain.User>(user);
            try
            {
                _factory.UsersLogic.Edit(mappedUser);
            }
            catch (Exception ex)
            {
                ViewData["error"] = "Ошибка при редактировании пользователя: " + ex.Message;
            }
            return RedirectToAction("List");
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Details(int id)
        {
            var user = _factory.UsersLogic.GetById(id);
            var mappedUser = Mapper.Map<modelViews.EditableUser>(user);
            return View(mappedUser);
        }

		[Authorize(Roles = "Admin")]
        public ActionResult FiredUsers()
        {
            var dbUsers = _factory.UsersLogic.GetAllFired();
            var mapedCollection = Mapper.Map<IEnumerable<domain.User>, IEnumerable<modelViews.User>>(dbUsers);
            return View(mapedCollection);
        }
    }
}